package socket_net_code.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class Demo3_MoreThread {
    public static void main(String[] args) throws InterruptedException {
        Receive receive = new Receive();
        receive.start();
        Send send = new Send();
        send.start();
    }
}

class Receive extends Thread {
    public Receive() {
    }

    @Override
    public void run() {
        try {
            //创建Socket相当于码头
            DatagramSocket socket = new DatagramSocket(9527);
            //创建Packet相当于创建集装箱
            DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
            while (true) {
                //接货，接收数据
                socket.receive(packet);
                //获取数据
                byte[] arr = packet.getData();
                //获取有效的字节个数
                int len = packet.getLength();
                //获取ip地址
                String ip = packet.getAddress().getHostAddress();
                //获取端口号
                int port = packet.getPort();
                System.out.println("ip地址：" + ip + " 端口号：" + port + ":" + "收到消息：" + new String(arr, 0, len));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }


        //socket.close();
    }
}

class Send extends Thread {
    public Send() {
    }

    @Override
    public void run() {
        try {
            Scanner sc = new Scanner(System.in);
            //创建Socket相当于创建码头
            DatagramSocket socket = new DatagramSocket();
            while (true) {
                String str = sc.nextLine();
                //创建Packet相当于集装箱
                DatagramPacket packet =
                        new DatagramPacket(
                                str.getBytes(), str.getBytes().length, InetAddress.getByName("192.168.106.194"), 9999);
                socket.send(packet);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
